<template>
  <s-layout :tabbarshow="false" id="layout" navbar="normal" :title="`新增招聘`" :autoBack="true" leftIconColor="$uni-text-color"
    :bgColor="'rgba(0,0,0,0)'" :titleStyle="{ color: '#fff', fontSize: '32rpx' }" :leftClick="leftClick">
    <view class="container"
      :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`, paddingTop: (safeAreaInsets?.top + 44) + 'px' }">

      <!-- 表单盒子 -->
      <view class="form_box area">
        <scroll-view scroll-y :enable-back-to-top="true" class="comprehensive">
          <!-- 表单结构 -->
          <uni-forms ref="relRef" v-model="state.formData" :rules="state.rules" validateTrigger="bind" labelWidth="120">
            <uni-forms-item name="project" label="部门：" required>
              <uni-easyinput @tap="chooseProject" placeholder="请选择部门" v-model="state.formData.project" :disabled="true"
                placeholder-class="placeholder_class" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>

            <uni-forms-item name="station" label="岗位：" required>
              <uni-easyinput @tap="chooseStation" placeholder="请选择岗位名称" v-model="state.formData.station"
                placeholder-class="placeholder_class" :disabled="true" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="treatment" label="福利待遇：" required>
              <uni-easyinput :disabled="true" @tap="chooseTreatment" placeholder="请选择福利待遇"
                v-model="state.formData.treatment" :inputBorder="false" placeholder-class="placeholder_class">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="company" label="公司：" required>
              <uni-easyinput :disabled="true" @tap="chooseCompanyName" placeholder="请选择公司名称"
                v-model="state.formData.company" :inputBorder="false" placeholder-class="placeholder_class">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="jobTitle" label="职位名称：" required>
              <uni-easyinput placeholder="请输入职位名称" v-model="state.formData.jobTitle" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="jobExperience" label="工作经验：" required>
              <uni-easyinput placeholder="请选择工作经验" :disabled="true" @tap="chooseJobExperience"
                v-model="state.formData.jobExperience" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="wage" label="工资：" required>
              <view class="wages">
                <input class="uni-input range_input" type="number" @input="changeWage"
                  v-model="state.formData.startWage" name="input" placeholder="工资范围开始" />
                <text class="range">~</text>
                <input class="uni-input range_input" type="number" @input="changeWage" v-model="state.formData.endWage"
                  name="input" placeholder="工资范围结束" />
              </view>
            </uni-forms-item>
            <uni-forms-item name="city" label="城市：" required>
              <uni-easyinput placeholder="请选择城市" v-model="state.formData.city" :disabled="true" :inputBorder="false"
                placeholder-class="placeholder_class" @tap="chooseCity()">
              </uni-easyinput>
            
            </uni-forms-item>
            <uni-forms-item name="contactWay" label="联系方式：" required>
              <uni-easyinput placeholder="请输入联系方式" v-model="state.formData.contactWay" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="sex" label="性别：" required>
              <view class="radio">
                <uni-data-checkbox v-model="state.formData.sex" :localdata="state.formData.sexlist" class="sex_box"
                  @change="checkSexChange"></uni-data-checkbox>
              </view>
            </uni-forms-item>
            <uni-forms-item name="menNumber" label="男（人数）：" required
              v-if="state.formData.sex == '1'|| state.formData.sex == '2' ">
              <uni-easyinput placeholder="请输入人数" type="number" v-model="state.formData.menNumber" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="womenNumber" label="女（人数）：" required
              v-if="state.formData.sex == '0'|| state.formData.sex == '2'  ">
              <uni-easyinput placeholder="请输入人数" type="number" v-model="state.formData.womenNumber"
                :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="date" label="截止日期：" required>
              <view class="dates" @tap="chooseDate" >
                <image :src="`${baseUrl}/uploads/uniapp_image/staff/class_icon01.png`"  mode="scaleToFill"/>
                <uni-easyinput placeholder="请选择日期" type="text" v-model="state.formData.date"
                :inputBorder="false" :disabled="true" >
              </uni-easyinput>
              </view>
            </uni-forms-item>
            <uni-forms-item name="address" label="详细地址：" required class="flex">
              <view class="flex-vertical">
                <uni-easyinput clearable :disabled="true" @tap="openMap" type="textarea"
                  v-model="state.formData.address" placeholder="请输入详细地址" @clear="state.formData.address = ''"
                  placeholder-class="placeholder_class"></uni-easyinput>
              </view>
            </uni-forms-item>
            <uni-forms-item name="content" label="内容：" required  prop="content" ref="content">
              <view class="flex-vertical">
                <editor id="editor" class="ql-container" placeholder="请输入内容" 
                          @input="contentInput($event)" @statuschange="onStatusChange" style="background-color: #F9F9F9;">
                </editor>
                <!-- <uni-easyinput type="textarea" v-model="state.formData.content" placeholder="请输入内容"></uni-easyinput> -->
              </view>
            </uni-forms-item>
          </uni-forms>

        </scroll-view>
      </view>

    </view>

  </s-layout>
  <!---日历选择-->
  <!-- 日期 单个 -->
  <up-calendar :closeOnClickOverlay="true" :show="show_single" :mode="mode_single" @confirm="confirm_single" @close="close_single"></up-calendar>
  <!-- 城市选择 -->
  <s-citypicker :show="showModifyArea" @confirmArea="confirmArea" @closeArea="closeArea"
                :closeOnClickOverlay="true"></s-citypicker>
  <!-- 底部弹出组件 && 项目弹出 -->
  <s-project-class @selectedData="switchTitle" 
    @subcomponentSearch="subcomponentSearch" :arrayList="projectDataList" ref="popupListRef"
  :searchBoxIsShow="false"   :showGoLink="'#'"></s-project-class>
  <!-- 岗位弹出  -->
  <s-popup-list @selectedData="stationSwitchTitle" :arrayList="stationDataList" ref="popupstationListRef"
    :popupTitle="'选择岗位'" :listingName="'列表名称'" :searchBoxIsShow="false" :isPage="false"
    :showGoLink="'#'"></s-popup-list>
  <!-- 福利待遇 -->
  <s-checkbox-list @selectedData="treatmentSwitchTitle" :arrayList="treatmentDataList" @pageEvent="pageTreatmentEvent"
    ref="popuptreatmentListRef" :current_page="treatmentCurrentPage" :last_page="treatmentLastPage"
    :popupTitle="'选择福利待遇'" :listingName="'列表名称'" :showGoLink="'#'"></s-checkbox-list>
  <!-- 公司名称 -->
  <s-popup-list @selectedData="companyNameSwitchTitle" :arrayList="companyNameDataList"
    @pageEvent="pageCompanyNameEvent" ref="popupCompanyNameListRef" :current_page="companyNameCurrentPage"
    :last_page="companyNameLastPage" :popupTitle="'选择公司名称'" :listingName="'列表名称'" :searchBoxIsShow="false"
    :showGoLink="'#'"></s-popup-list>
  <!-- 工作年限 -->
  <up-action-sheet :show="showStatus" :actions="showStatusActions" title="请选择状态" @close="showStatus = false"
    @select="statusSelect" :round="18" :closeOnClickAction="true">
  </up-action-sheet>


  <up-modal :show="upmodalshow" @confirm="confirm" ref="uModal" :asyncClose="true">
  </up-modal>
    <!-- 底部提交按钮 -->
    <view>
    <s-button @netWork="submitForm" :text="!editid?text:edittext"></s-button>
  </view>
</template>

<script setup>
import sheep from '@/sheep';
import { ref, reactive, unref } from 'vue';
import { onLoad,onUnload } from '@dcloudio/uni-app';
import { baseUrl } from "@/sheep/config";
const { safeAreaInsets } = uni.getSystemInfoSync();  
import { wage, project, station, sex, treatment, company, jobTitle, jobExperience, city, contactWay, menNumber, womenNumber, date, address, content } from '@/sheep/validate/form';
const text = ref("提交");
const edittext =  ref('修改')
	// 页面销毁的时候将监听事件清掉 
const upmodalshow = ref(false)

  // 单个
  const chooseDate =()=>{
    show_single.value = true
  }
  const mode_single = ref('single')
  const show_single = ref(false)

  const confirm_single = (e) => {
    state.formData.date= `${e}`
    close_single()
  }
  const close_single = () =>   {
    show_single.value = false
  }
const confirm = () => {  
    setTimeout(() => {  
        // 3秒后自动关闭  
        upmodalshow.value = false;  
    }, 3000);  
};  
  const leftClick = ()=>{
    upmodalshow.value = true;  
  }
	onUnload(() => {
    upmodalshow.value = true
    // uni.$off('receive'); // 清除名为'receive'的事件监听器
	})
const state = reactive({
  fileList1: [],
  formData: {
    project: '',//项目
    station: '',//岗位
    sex: '',//性别
   
    sexlist: [{
      text: '男',
      value: 1,
      checked: true
    },
    {
      text: '女',
      value: 0,
      checked: false
    },
    {
      text: '男女不限',
      value: 2,
      checked: false
    }],
    treatment: '',//待遇
    company: '',//公司
    jobTitle: '',//职位名称
    jobExperience: '',//工作经验
    wage: '',//工资
    startWage: '',//开始工资
    endWage: '',//结束工资
    city: '',//城市
    contactWay: '',//联系方式
    menNumber: '',//男人数
    womenNumber: '',//女人数
    date: '',//截止日期
    address: '',//详细地址
    content: '',//内容
    lon:'',//经度
    lat:'',//纬度
  },
  rules: {
    wage,
    project,
    station,
    sex,
    treatment,
    company,
    jobTitle,
    jobExperience,
    city,
    contactWay,
    menNumber,
    womenNumber,
    date,
    address,
    content,

  },
});
const chooseCity = () => {
  showModifyArea.value = true
}
// 城市选择
const showModifyArea = ref(false)
const confirmArea = (e) => {
  state.formData.city = e.join(',')
  showModifyArea.value = false
}
const closeArea = () => {
  showModifyArea.value = false
}

  const  editid = ref('')
onLoad((options) => {
  editid.value = options.ids
  if(options.ids){
    getListDetail()
  }
  let params={
    is_all:'1',
    is_include_main:'1'
  }
  projectList(params)
  stationtList()
  benefitsList()
  companyNameList()
   // 获取经纬度 && 详细地址
 uni.$on('receive',(e) => {
    state.formData.address = ''
    state.formData.lon = ''
    state.formData.lat = ''
    state.formData.address = e.locationAddress  // 详细地址
    state.formData.lon = e.locationLon    // 经度
    state.formData.lat = e.locationLat    // 纬度
  })
  // uni.$off('receive')
})

//请求招聘详情
const getListDetail = async()=>{
  let parpam={
    ids: editid.value
  }
  const res = await sheep.$api.recruit.getListDetail(parpam);
  state.formData.address = res?.data.address//地址
  state.formData.city = res?.data.city//城市
  state.formData.contactWay = res?.data.contact //联系方式
  state.formData.date = res?.data.end_date //截止时间
  state.formData.jobTitle = res?.data.title//职位名称
  state.formData.company = res?.data.company.title //公司名称
  state.formData.jobExperience = res?.data.experience //工作经验
  state.formData.startWage = res?.data.salary_start //开始工资
  state.formData.endWage = res?.data.salary_end //结束工资
  state.formData.womenNumber = res?.data.woman_num //女人数
  state.formData.menNumber = res?.data.man_num //男人数
  state.formData.content = res?.data.content //内容
  state.formData.sex =  res?.data.gender_limit//性别
  state.formData.station =  res?.data.post.title//岗位名称
  state.formData.lon = res?.data.lon //精度
  state.formData.lat =  res?.data.lat//维度
  treatment_id.value =  res?.data.benefits_id //福利待遇id
  companyName_id.value = res?.data.company_id //公司id
  station_id.value = res?.data.post_id//招聘信息id
  project_id.value = res?.data.department.id//项目id
  state.formData.wage = res?.data.salary_start //工资总数
  //福利待遇
  const  item = res?.data.benefits
  const itemids = ref([])
  const itemtitle = ref([])
  item.forEach(element => {
    itemids.value.push(element.id)
    itemtitle.value.push(element.title)
  });
  state.formData.treatment = itemtitle.value.join(',')
  state.formData.project =  res?.data.department.company.name + '/' +res?.data.department.name//项目名称
} 
//详细地址
const openMap =()=>{
  uni.navigateTo({
    url:'../../project/change_location'
  })
}

//性别选择
const checkSexChange = (value) => {
  state.formData.sex = value.detail.value
}

//工资范围
const changeWage = () => {
  if (state.formData.startWage) {
    state.formData.wage = state.formData.startWage
  }
  if (state.formData.endWage) {
    state.formData.wage = state.formData.endWage
  }

}
//项目选择 // 切换项目------------------------
const chooseProject = () => {
  popupListRef.value.open()
}
const popupListRef = ref()
// 调用接口：获取项目列表
const projectDataList = ref([])
const projectList = async (params = null) => {
  const res = await sheep.$api.app.getDepartment(params);
  projectDataList.value = res.data;
};

// 搜索项目列表
const subcomponentSearch = (value) => {
  projectDataList.value = []
  let params = {
    filter: JSON.stringify({
      title: value,
    }),
    op: JSON.stringify({
      title: 'LIKE',
    })
  };
  projectList(params);
}
// 项目id
const project_id = ref()

// 子组件触发的方法将项目title改变
const switchTitle = (data) => {
  state.formData.project = data.jointTitles
  project_id.value = data.id
}
// 岗位选择开始------------------------------------------
const chooseStation = () => {
  popupstationListRef.value.open()
}
//岗位
const popupstationListRef = ref()
const stationDataList = ref([])
const stationtList = async (params = null) => {
  const res = await sheep.$api.recruit.getStationtList(params);
  stationDataList.value = [...stationDataList.value, ...res?.data.rows];
};



const station_id = ref()
// 子组件触发的方法将项目title改变 岗位
const stationSwitchTitle = (data) => {
  state.formData.station = data.title
  station_id.value = data.id
}
//------------------ 岗位选择结束-----------------------


//------------------ 福利待遇开始-----------------------
const popuptreatmentListRef =  ref()
const treatment_id = ref()
// 调用接口：获取项目列表
const treatmentDataList = ref([])
const benefitsList = async(params = null)=>{
  const res = await sheep.$api.recruit.getBenefitsList(params);
  treatmentDataList.value = [...treatmentDataList.value, ...res?.data.rows];  
  treatmentCurrentPage.value = res.data.current_page;
  treatmentLastPage.value = res.data.last_page;
}
const chooseTreatment = ()=>{
  popuptreatmentListRef.value.open()

}
// 子组件触发的方法将项目title 福利待遇
const treatmentSwitchTitle = (item) => {
  const optionstitle = ref([])
  const optionsid = ref([])
  item.forEach(element => {
    optionsid.value.push(element.id)
    optionstitle.value.push(element.title)
  });
  optionstitle.value = optionstitle.value.join(',')
  optionsid.value = optionsid.value.join(',')

  state.formData.treatment = optionstitle.value
  treatment_id.value = optionsid.value
}
const treatmentCurrentPage =  ref()
const treatmentLastPage = ref()
const  treatmentpage = ref(1)
const pageTreatmentEvent =()=>{
  if (treatmentCurrentPage.value < treatmentLastPage.value) {
    treatmentpage.value += 1;
  } else {
    return;
  }
  let params = {
    page: treatmentpage.value,
  };
  benefitsList(params);
}
//------------------ 福利待遇结束-----------------------
//------------------ 公司名称开始-----------------------
const popupCompanyNameListRef =  ref()
const companyName_id = ref()
// 调用接口：获取项目列表
const companyNameDataList = ref([])
const companyNameList = async(params = null)=>{
  const res = await sheep.$api.recruit.getCompanytList(params);
  companyNameDataList.value = [...companyNameDataList.value, ...res?.data.rows];
  
  companyNameCurrentPage.value = res.data.current_page;
  companyNameLastPage.value = res.data.last_page;
}
const chooseCompanyName = ()=>{
  popupCompanyNameListRef.value.open()

}
// 子组件触发的方法将项目title 福利待遇
const companyNameSwitchTitle = (data) => {
  state.formData.company = data.title
  companyName_id.value = data.id
}
const companyNameCurrentPage =  ref()
const companyNameLastPage = ref()
const  companyNamepage = ref(1)
const pageCompanyNameEvent =()=>{
  if (companyNameCurrentPage.value < companyNameLastPage.value) {
    companyNamepage.value += 1;
  } else {
    return;
  }
  let params = {
    page: companyNamepage.value,
  };
  companyNameList(params);
}
//------------------ 公司名称结束-----------------------
//------------------ 工作年限开始-----------------------
//选择类型
const chooseJobExperience = () => {
  showStatus.value = true
}
const showStatus = ref(false)
const showStatusActions = ref([
  { name: '1-3年', is_entry: 1 },
  { name: '3-5年', is_entry: 2 },
  { name: '5-10年', is_entry: 3 },
  { name: '10年以上', is_entry: 4 }
])
// 定义方法  状态
const is_entry = ref()
function statusSelect(e) {
  is_entry.value = e.is_entry
  state.formData.jobExperience = e.name
  showStatus.value = false

}
//------------------ 工作年限结束-----------------------
// 用工需求
const contentInput = (e) => {
  state.formData.content = e.detail.html
}
//项目提交
const relRef = ref();
const submitForm = async () => {
  // #ifdef MP
  sheep.$platform.useProvider('wechat').subscribeMessage(['apply_notice','apply_result_notice']);
        // #endif
  const validate = await unref(relRef)
    .validate()
    .catch((error) => {
    });
  if (!validate) return;
  uni.$u.throttle(() => {
  let params = {
    post_id:station_id.value,//招聘信息id
    payment_type: state.formData.meansOfPayments,//结算方式
    benefits_id:treatment_id.value,//福利待遇
    company_id:companyName_id.value,//公司id
    gender_limit:state.formData.sex,//性别
    man_num:state.formData.menNumber,//男人数
    woman_num:state.formData.womenNumber,//女人数
    title:state.formData.jobTitle,//职位名称 
    salary_start:state.formData.startWage,//开始工资
    salary_end:state.formData.endWage,//结束工资
    experience:state.formData.jobExperience,//工作经验
    content:state.formData.content,//内容
    city:state.formData.city,//城市
    lon:state.formData.lon,//经度
    lat:state.formData.lat,//维度
    address:state.formData.address,//地址
    end_date:state.formData.date,//戒指日期
    contact:state.formData.contactWay,//联系方式
    department_id:project_id.value,//项目id
    ids:editid.value
  }
   const res = ref()
  //  if(!editid.value){
     res.value = sheep.$api.recruit.postRecruitmentAdd(params);  

  //  }else{
  //   //修改
  //    res.value = sheep.$api.recruit.postRecruitmentEdit(params);
    
  //  }
  // console.log( res.value)
  if (res.value.code == 1) {
     
        setTimeout(() => {
            sheep.$router.back(true)
          }, 500)
   
    } else {
      setTimeout(() => {
            sheep.$router.back(true)
        }, 500)
    }
  }, 1000)
}

</script>

<style scoped lang="scss">
@import '../compentns/public.scss';
     @import '../compentns/up_sheet.scss';
.comprehensive{
  width: 100% !important;
  margin: 0 !important;
}
.flex {
  background: red;
}

:deep(.uni-forms) {
  .uni-forms-item.is-direction-left {
    &:nth-last-child(2) {
      .uni-forms-item__label {
        background: $uni-bg-color;
      }

      flex-direction: column !important;
      height: auto;
    }

  }

  .uni-forms-item.is-direction-left {
    &:last-child {
      .uni-forms-item__label {
        background: $uni-bg-color;
      }

      flex-direction: column !important;
      height: auto;
    }

  }
}

:deep(.is-disabled) {
  .uni-easyinput__placeholder-class {
    color: #666 !important;
  }
}
:deep(.is-textarea) {
  .uni-easyinput__placeholder-class {
    color: #999 !important;
  }
  .uni-easyinput__content-textarea{
    color: #353434 !important;
  }
}
:deep(.is-disabled){
  .uni-easyinput__placeholder-class{
    color: $uni-color-primary !important;
  }   

}
:deep(.uni-calendar--fixed ){
  width: 100% !important;
}
:deep(.uni-calendar__mask){
  width: 100% !important;
}
//日期
.dates{
  width: 278rpx;
  text-align: right;
  border: #1241E2 1rpx solid;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 16rpx;
  height: 64rpx;
  margin: 15rpx 0 0 200rpx;
  image{
    width: 28rpx;
    height: 26rpx;
    margin-right: 10rpx;
    padding-left: 20rpx;
  }
  .placeholder{
    color: $uni-color-primary;
    font-weight: 500;
   font-size:$uni-font-size-26;
  }
  .gray{
    color: #999;
    font-weight: 500;
   font-size:$uni-font-size-26;
  }
  :deep(.uni-easyinput__content-input){
    text-align: left !important;
  }
}
:deep(.ql-container){
  font-style: normal;
  padding: 10rpx 20rpx;
}
</style>